CC = gcc

srcdir = src
testdir = test
objdir = build
target = tgnews
target_trainer = tgnews_trainer
target_lib = $(objdir)/libtgnews.a
LDFLAGS := -L$(objdir) \
	-l$(subst lib,,$(basename $(notdir $(target_lib))))
CFLAGS := -std=c11 -Wall -Wextra -Wpedantic -O0

includes_lib := -I$(srcdir)

src := $(wildcard $(srcdir)/*/*.c)
src_target_trainer := $(srcdir)/main_trainer.c
src_target := $(srcdir)/main.c
src_test := $(wildcard $(testdir)/*/*.c)
obj_target_trainer := $(src_target_trainer:$(srcdir)/%.c=$(objdir)/%.o)
obj_target := $(src_target:$(srcdir)/%.c=$(objdir)/%.o)
obj := $(src:$(srcdir)/%.c=$(objdir)/%.o)
obj_test := $(src_test:$(testdir)/%.c=$(objdir)/test/%.o)
obj_all := $(obj) $(obj_target) $(obj_target_trainer)
dep := $(obj:%.o=%.d)
dep_test := $(obj_test:%.o=%.d)

all: output_directories $(target_lib) $(target) $(target_trainer)

debug: $(eval CFLAGS += -g) all
test_debug: $(eval CFLAGS += -g) test

output_directories:
	@mkdir -p $(objdir) $(dir $(obj))

output_directories_test:
	@mkdir -p $(objdir) $(dir $(obj_test))

$(target_lib): $(obj)
	ar rcs $@ $^

$(target_trainer): $(obj_target_trainer) $(target_lib)
	$(CC) -o $@ $^ $(LDFLAGS)

$(target): $(obj_target) $(target_lib)
	$(CC) -o $@ $^ $(LDFLAGS)

target_parser_tests := $(shell basename $(src_test) .c )

$(target_parser_tests): $(obj_test) $(target_lib)
	$(CC) -o $@ $^ $(LDFLAGS)

test: output_directories output_directories_test $(target_parser_tests)

-include $(dep)
$(obj_all): $(objdir)/%.o : $(srcdir)/%.c
	$(CC) $(CFLAGS) -o $@ -MMD -c $< $(includes_lib)
-include $(dep_test)
$(obj_test): $(objdir)/%.o : %.c
	$(CC) $(CFLAGS) -o $@ -MMD -c $< $(includes_lib)

.PHONY: clean output_directories debug
clean:
	@rm -fr build
	@rm -f $(target) $(target_trainer) $(target_parser_tests)
